import axios, { InternalAxiosRequestConfig } from "axios";
import { LINKS } from "./link";
import { ElMessage } from "element-plus";

// axios.defaults.headers.post['Content-Type'] = 'application/json';
const env = import.meta.env;
console.log(env);
console.log(env.VITE_APP_BASE_API);

const RequestURL_Map = new Map();
const DefaultConfig = {
  baseURL: '/api',
  headers: {},
};
const api = axios.create(DefaultConfig);

//白名单，不进行提示消息
const whiteList: string[] = [];

// http response 拦截器
api.interceptors.response.use(
  response => {
    const Key = `${response.config.baseURL}${
      response.config.url
    }${JSON.stringify(response.config.params ?? {})}${JSON.stringify(
      response.config.data ?? {}
    )}`;
    if (RequestURL_Map.has(Key)) {
      RequestURL_Map.delete(Key);
    }

    if (response.status === 200) {
      switch (response.data.code) {
        case 200:
          return Promise.resolve(response);
        default:
          //判断参数返回的时候否是流文件
          if (response.data instanceof Blob) {
            return Promise.resolve(response);
          }
          console.error(response);
          if (whiteList.includes(response.config.url)) {
            return Promise.reject(response);
          }
          ElMessage({
            message: response.data.message,
            type: "error",
            duration: 1000,
          });
          return Promise.reject(response);
      }
    } else {
      console.error(response);
      ElMessage({
        message: response.data.message,
        type: "error",
        duration: 1000,
      });
      return Promise.reject(response);
    }
  },
  //接口错误状态处理，也就是说无响应时的处理
  error => {
    console.error(error);
    ElMessage({ message: error.message, type: "error", duration: 1000 });
    // 若不希望接口401跳转登录 注释这个判断里面逻辑
    if (error.response.status === 401) {
      localStorage.removeItem("token");
      setTimeout(() => {
        window.location.href = window.location.href;
      }, 1000);
      return;
    }
    return Promise.reject(error); // 返回接口返回的错误信息
  }
);

export async function request(url: string, config?: any, notoken = 0) {
  console.log(url,config);
  
  const Key = `${DefaultConfig.baseURL}${url}${JSON.stringify(
    config?.params ?? {}
  )}${JSON.stringify(config?.data ?? {})}`;
  const controller = new AbortController();
  if (RequestURL_Map.has(Key)) {
    const controller = RequestURL_Map.get(Key);
    controller.abort();
    RequestURL_Map.delete(Key);
  }
  RequestURL_Map.set(Key, controller);

  const body = {
    url,
    ...Object.assign({}, config, { signal: controller.signal }),
  };

  if (notoken == 0 && localStorage.getItem("token")) {
    try {
      body.headers.authorization = `Bearer ${localStorage.getItem("token")}`;
    } catch (err) {
      body.headers = {};
      body.headers.authorization = `Bearer ${localStorage.getItem("token")}`;
    }
  }

  const response = await api.request(body);
  let result;
  if (response.data instanceof Blob) {
    result = response;
  } else {
    result = response.data;
  }
  return result;
}

export async function request_post(url, config) {
  return request(url, { method: "post", ...config });
}

export async function request_post_notoken(url, config) {
  return request(url, { method: "post", ...config }, 1);
}
